import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_app_update/flutter_app_update.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/api/req/user/req_user.dart';
import 'package:flutter_changdian_football/global.dart';
import 'package:flutter_changdian_football/model/other/protocol_model.dart';
import 'package:flutter_changdian_football/model/user/self_center_model.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/utils/custom_toast.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/utils/share_util.dart';
import 'package:flutter_changdian_football/utils/str_utils.dart';
import 'package:flutter_changdian_football/widget/dialog/upgrade_dialog.dart';
import 'package:flutter_changdian_football/widget/sheet/share_icon_sheet.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

class UserStore extends GetxController {
  static UserStore get to => Get.find();

  // 常用功能
  List commonFunList = [
    {
      'text': '我的关注',
      'icon': 'assets/images/icon_me_gz.png',
    },
    {
      'text': '分享推荐',
      'icon': 'assets/images/icon_me_fx.png',
    },
    {
      'text': '应用设置',
      'icon': 'assets/images/icon_me_sz.png',
    },
    {
      'text': '关于我们',
      'icon': 'assets/images/icon_me_gy.png',
    },
    {
      'text': '使用帮助',
      'icon': 'assets/images/icon_me_sy.png',
    },
    {
      'text': '等级介绍',
      'icon': 'assets/images/icon_vip_intro.png',
    },
    {
      'text': '意见反馈',
      'icon': 'assets/images/yjfk.png',
    },
    {
      'text': '联系客服',
      'icon': 'assets/images/lxkf.png',
    },
    // {
    //   'text': '测试登录页',
    //   'icon': 'assets/images/lxkf.png',
    // }
  ];

  // 跳转页面
  toPage(index) async {
    if (index == 0) {
      // 我的关注
      if (checkLoginPage()) {
        Get.toNamed(AppRoutes.myConcerns);
      }
    } else if (index == 1) {
      try {
        EasyLoading.show();
        var resp = await ReqOther.getProtocol(CustomConstant.SHARE_IMAGE);

        if (resp.data['code'] == '200') {
          // protocolModel = ProtocolModel.fromJson(resp.data['data']);
          // 分享推荐
          ShareIconSheet.shareIcon(
            null, 
            null, 
            resp.data['data']['url'], 
            null,
            isShowImg: true,
            wxTap: () {
              ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "0");
            },
            pyqTap: () {
              ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "1");
            },
            qqTap: () {
              ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "2");
            },
            wbTap: () {
              ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "3");
            },
          );
          update();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } catch (e) {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      } finally {
        EasyLoading.dismiss();
      }
    } else if (index == 2) {
      // 应用设置
      if (checkLoginPage()) {
        Get.toNamed(AppRoutes.applicationSetting);
      }
    } else if (index == 3) {
      // 关于我们
      Get.toNamed(AppRoutes.aboutUs);
    } else if (index == 4) {
      // 使用帮助
      Get.toNamed(AppRoutes.usingHelp);
    } else if (index == 5) {
      // 等级介绍
      Get.toNamed(AppRoutes.inAppWebView, parameters: {
        'title': '等级介绍',
        'type': CustomConstant.LEVEL_INTRODUCTION,
      });
    } else if (index == 6) {
      // 意见反馈
      if (checkLoginPage()) {
        Get.toNamed(AppRoutes.feedback);
      }
    } else if (index == 7) {
      // 联系客服
      Get.toNamed(AppRoutes.contactCustomerService);
    } else if (index == 8) {
      // 测试登录
      Get.toNamed(AppRoutes.login);
    }
  }

  bool isLogin = false;
  changeLogin() {
    String? accessToken = SpUtil.getString("Authorization");
    if (accessToken == null) {
      isLogin = false;
    } else {
      isLogin = true;
    }
  }

  @override
  void onInit() {
    super.onInit();

    getUserInfo();


    AzhonAppUpdate.listener((map) {
      // logger.d('==================${map}');
      downloadType = map['type'];
      
      if (map['type'] == 'start') {
        /// 开始下载通知
      } else if (map['type'] == 'downloading') {
        downloadProgress = double.parse('${map['progress']}') / double.parse('${map['max']}');
        update();
      } else if (map['type'] == 'done') {
        /// 下载完成通知，安装包路径 {type: done, apk: /storage/emulated/0/Android/data/com.wetax/cache/深圳税务.apk}
        // CustomToast.showTextToast('下载成功，文件存储地址：${map['apk']}');
        update();
      } else if (map['type'] == 'cancel') {
        // CustomToast.showTextToast('您已取消下载');
        update();
        /// 取消下载通知
      } else if (map['type'] == 'error') {
        /// 下载出错
        CustomToast.showTextToast('下载失败', position: EasyLoadingToastPosition.bottom);
        update();
      }
    });

    eventBus.on<BottomNavigationBarEvent>().listen((event) {
      if (event.message == CustomConstant.EVENT_REFRESH) {
        // 刷新数据
        getUserInfo();
      } else if (event.message == CustomConstant.EVENT_LOGOUT_REFRESH) {
        isLogin = false;
        selfCenterModel = null;
        Global.accessToken = '';
        SpUtil.containsKey("Authorization");
        update();
      }
    });
  }

  SelfCenterModel? selfCenterModel;
  /// 获取用户信息
  getUserInfo() async {
    var resp = await ReqUser.selfCenter();
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        isLogin = true;
        selfCenterModel = SelfCenterModel.fromJson(resp.data['data']);

        await setDeviceToken();
      } else {
        isLogin = false;
      }
    } else {
      isLogin = false;
    }
    update();
  }

  /// 设置用户手机deviceToken
  setDeviceToken() async {
    Map<String, dynamic> map = await MobpushPlugin.getRegistrationId();
    await ReqOther.setDeviceToken(deviceToken: map['res']);
  }

  /// 跳转页面
  checkLoginPage()  {
    if (isLogin == true && Global.accessToken != '') {
      return true;
    } else {
      Get.toNamed(AppRoutes.login);
      return false;
    }
  }




  var downloadType = '';
  var downloadProgress = 0.0;

  /// 检查版本
  checkVersion(bool isToast) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;

    if (isToast == true) {
      EasyLoading.show();
    }

    var resp = await ReqOther.versionCheck();
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        if (resp.data['data'] == null) {
          CustomToast.showTextToast('当前已是最新版本');
          return ;
        }
        if (StrUtils.isUpdateVersion(resp.data['data']['version'] ?? '', version) == false && Platform.isAndroid) {
          if (isToast == true) {
            CustomToast.showTextToast('当前已是最新版本');
          }
          return ;
        }

        if (StrUtils.isUpdateVersion(resp.data['data']['version'] ?? '', version) == false && Platform.isIOS) {
          if (isToast == true) {
            CustomToast.showTextToast('当前已是最新版本');
          }
          return ;
        }

        bool is64 = false;
        if (Platform.isAndroid) {
          DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
          AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
          if ((androidInfo.data['supportedAbis'] as List).contains('arm64-v8a')) {
            is64 = true;
          }
        }
        

        UpgradeDialog.upgradeDialog(
          Get.context!,
          version: '${resp.data['data']['version']}',
          versionContent: '${Platform.isIOS ? resp.data['data']['updateContent'] ?? '暂无更新内容' : resp.data['data']['updateContent'] ?? '暂无更新内容'}',
          forcedUpgrade: resp.data['data']['isEnforce'] == true ? true : false,
          confirmTap: () {
            if (resp.data['data']['isEnforce'] == false && !Platform.isIOS) {
              Get.back();
            }
            if (Platform.isAndroid) {
              if (is64 && resp.data['data']['apkUrl'] == null) {
                CustomToast.showTextToast('暂无可用地址');
                return ;
              }
              if (is64 && resp.data['data']['apkUrl'] == null) {
                CustomToast.showTextToast('暂无可用地址');
                return ;
              }
              _appUpdate(apkUrl: is64 ? "${resp.data['data']['apkUrl']}" : "${resp.data['data']['apkUrl']}");
            } else if (Platform.isIOS) {
              if (resp.data['data']['iosUrl'] == null) {
                CustomToast.showTextToast('IOS 暂无可用下载链接', position: EasyLoadingToastPosition.bottom);
                return ;
              }
              _launchAppStore(Uri.parse('${resp.data['data']['iosUrl']}'));
            }
          }
        );

      }
    } else {
      if (isToast) {
        CustomToast.showTextToast('系统繁忙，请稍后再试!');
      }
    }
  }

  /// 下载apk安装包
  _appUpdate({String apkUrl = '', String iosUrl = ''}) {
    UpdateModel model = UpdateModel(
      apkUrl,
      "畅点足球.apk",
      "ic_launcher",
      iosUrl,
    );
    AzhonAppUpdate.update(model).then((value) => logger.d('$value'));
  }

  /// 跳转AppStore
  Future<void> _launchAppStore(Uri url) async {
    if (!await launchUrl(
      url,
      mode: LaunchMode.externalApplication,
    )) {
      CustomToast.showTextToast('IOS 下载地址错误', position: EasyLoadingToastPosition.bottom);
    }
  }

  /// 注销
  logOff() async {
    isLogin = false;
    selfCenterModel = null;
    Global.accessToken = '';
    SpUtil.remove("Authorization");
    eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_LOGOUT_REFRESH));
    update();
  }

  /// 退出登录
  logOut() {
    isLogin = false;
    selfCenterModel = null;
    Global.accessToken = '';
    SpUtil.remove("Authorization");
    eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_LOGOUT_REFRESH));
    update();
  }

}